{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-02-17T03:18:04.707414Z",
     "start_time": "2025-02-17T03:18:04.703412Z"
    }
   },
   "source": [
    "\n",
    "import jieba\n",
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "from wordcloud import WordCloud\n",
    "from collections import Counter"
   ],
   "execution_count": 20,
   "outputs": []
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-17T09:19:19.305083Z",
     "start_time": "2025-02-17T09:19:17.810631Z"
    }
   },
   "cell_type": "code",
   "source": [
    "all_word = []\n",
    "\n",
    "stop_words = []\n",
    "with open('../data/cn_stopwords.txt', encoding='utf-8') as f:\n",
    "    lines = f.readlines()\n",
    "    for line in lines:\n",
    "        stop_words.append(line.strip())\n",
    "stop_words.append(' ')\n",
    "\n",
    "with open('../data/三体.txt', encoding='utf-8') as f:\n",
    "    lines = f.readlines()\n",
    "    for line in lines:\n",
    "        cut_list = jieba.lcut(line.strip(), cut_all=False)\n",
    "        all_word.extend([word for word in cut_list if word not in stop_words])\n",
    "\n",
    "# 使用Counter统计词频\n",
    "word_counts = Counter(all_word)\n",
    "# 获取出现次数最多的前N个词\n",
    "most_common_words = word_counts.most_common(30)  # 获取前10个最常见的词\n",
    "\n",
    "# 打印结果\n",
    "for word, count in most_common_words:\n",
    "    print(f\"'{word}': {count}次\")\n",
    "xxx = [words[0] for words in most_common_words]\n",
    "space_separated_word = ' '.join(xxx)\n",
    "font_path = \"C:/Windows/Fonts/simhei.ttf\"  # 黑体字体路径\n",
    "\n",
    "wordcloud = WordCloud(max_words=100, font_path=font_path).generate(space_separated_word)\n",
    "plt.figure(figsize=(10, 8))\n",
    "plt.imshow(wordcloud, interpolation='bilinear')\n",
    "plt.axis('off')\n",
    "plt.show()"
   ],
   "id": "3f450065df0aaa0e",
   "execution_count": 42,
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
